package com.momo.task.website;

import com.momo.common.common.JSONResult;
import com.momo.common.error.RedisKeyEnum;
import com.momo.common.util.RedisUtil;
import com.momo.mapper.dao.WebsiteVisibleDAO;
import com.momo.mapper.dataobject.WebsiteVisibleDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;

/**
 * Created by MOMO on 2019/4/24.
 */
@Slf4j
@Component
public class TebsiteVisitTask {
    @Autowired
    private RedisUtil redisUtil;
    private Long beforeTotal = 0L;
    @Autowired
    private WebsiteVisibleDAO websiteVisibleDAO;

    /**
     * Redis挂掉了，查询数据库
     *
     * @return
     */
    public JSONResult visitPeopleToRedis() {

        WebsiteVisibleDO websiteVisibleDO = websiteVisibleDAO.getById(1L);
        WebsiteVisibleDO entity = new WebsiteVisibleDO();
        entity.setId(1L);
        entity.setVisibleNumber(websiteVisibleDO.getVisibleNumber() + 1);
        redisUtil.set(RedisKeyEnum.REDIS_KEY_WEBSITE_VISIBLE_TOTAL.getKey(), String.valueOf(websiteVisibleDO.getVisibleNumber() + 1));
        websiteVisibleDAO.update(entity);
        return JSONResult.ok("网站访问人数变更成功");
    }

    //统计网站访问总次数
    @Scheduled(cron = "59 * * * * ? ")
    public Long visitPeople() {
        //网站访问人数
        Object total = redisUtil.get(RedisKeyEnum.REDIS_KEY_WEBSITE_VISIBLE_TOTAL.getKey());
        Long totalPeople = Long.valueOf(String.valueOf(total == null ? "1" : total));
        if (!totalPeople.equals(beforeTotal)) {
            WebsiteVisibleDO entity = new WebsiteVisibleDO();
            beforeTotal = totalPeople;
            entity.setId(1L);
            entity.setVisibleNumber(beforeTotal + 1);
            websiteVisibleDAO.update(entity);

            return entity.getVisibleNumber();
        }
        return totalPeople;
    }
}
